package com.enlorenz.core.engine.imp.thread;

import com.enlorenz.common.util.DataDetUtils;
import com.enlorenz.core.engine.AbstractEngine;
import com.enlorenz.core.engine.IBuzHandler;
import com.enlorenz.core.engine.exception.EngineControlException;

/**
 * 循环控制线程
 * @author lcb
 */
public class ControlThread extends AbstractEngine{
	//内部线程
	private InnerCycleThread innerThread;
	//业务处理类
	protected IBuzHandler buzHandler;
	
	/**
	 * 初始化控制线程
	 */
	protected void initEngine() throws EngineControlException{
		innerThread=new InnerCycleThread();
		//设置线程的名称
		if(!DataDetUtils.isStrEmpty(this.getName())){
			innerThread.setName(this.getName());
		}
	}
	
	
	/**
	 * 判断引擎是否存活
	 */
	@Override
	public boolean isAlive() {
		//判断线程是否存活
		if(!innerThread.isAlive()){
			return false;
		}
		//判断线程标识是否为true
		if(!innerThread.isRunFlag()){
			return false;
		}
		return true;
	}
	
	
	@Override
	protected void shutdownEngine() throws EngineControlException{
		if(null!=innerThread){
			innerThread.setRunFlag(false);
			innerThread.interrupt();
			//innerThread.stop();
		}
	}

	@Override
	protected void startEngine() throws EngineControlException{
		if(null!=innerThread){
			innerThread.setRunFlag(true);
			innerThread.start();
		}
	}
	
	/**
	 * 循环开始需要进行的操作
	 * @throws Exception
	 */
	protected void doWhenStart() throws Exception{
		
	}
	
	/**
	 * 循环结束需要进行的操作
	 * @throws Exception
	 */
	protected void doWhenEnd() throws Exception{
		
	}
	
	/**
	 * 内部循环线程
	 * @author lcb
	 */
	private class InnerCycleThread extends Thread{
		//运行标识
		private boolean runFlag;
		
		public boolean isRunFlag() {
			return runFlag;
		}

		public void setRunFlag(boolean runFlag) {
			this.runFlag = runFlag;
		}

		public void run(){
			while(runFlag){
				try {
					//逻辑开始需要执行的
					doWhenStart();
					//执行业务
					buzHandler.handle();
					//逻辑结束需要执行的
					doWhenEnd();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	/**
	 * 设置业务处理器
	 * @param buzHandler 业务处理器
	 */
	public void setBuzHandler(IBuzHandler buzHandler) {
		this.buzHandler = buzHandler;
	}
	
}
